local http = require "lib.http"

local config = {
	root = "../extra/http-esvr/"
}

local function route(http_header, url)
	local cgi_name = url
	pos = string.find(url, "/")
	if pos then
		cgi_name = string.sub(cgi_name, 1, pos - 1)
	end
	local cgi_module = nil
	local status, err = pcall(function() cgi_module = require (cgi_name) end)
	if cgi_module then
		return cgi_module(http_header, url)
	end
end

function on_http(request)
	local header = http.parse_request(request)
	url = header:get_url()
	if url then
		local msg = route(header, url)
		if msg then
			if url:sub(-3) == ".js" then
				return header:render_response_js(msg)
			elseif url:sub(-4) == ".css" then
				return header:render_response_css(msg)
			else
				return header:render_response_html(msg)
			end
		else
			return header:render_response_404()
		end
	else
		return header:render_response_404()
	end
end
